<?php

namespace app\index\controller;

use app\common\controller\HomeBase;
use Wechat;

class Pay extends HomeBase
{
    public function index()
    {
        return $this->fetch('pay/index');
    }

    /**
     * 支付通知处理
     *
     * @return type
     */
    public function notify()
    {
        header('Content-Type:text/xml; charset=utf-8');
        $postStr    = file_get_contents("php://input");
        $notifyInfo = ( array )simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($notifyInfo ['result_code'] == 'SUCCESS' && $notifyInfo ['return_code'] == 'SUCCESS') {
            // 记录支付通知信息
            file_put_contents(LOG_PATH . 'pay_notify.log', var_export($notifyInfo, true));
            // 所有操作成功，返回正常状态
            return xml(['return_code' => 'SUCCESS', 'return_msg' => 'SAVE DATA SUCCESS']);
        }
    }

    /**
     * 生成预支付码
     *
     * @return type
     */
    public function qrc()
    {
        $outer_no = input('outer_no');
        $price    = input('price');
        if (empty ($outer_no) || empty ($price)) {
            return ['code' => 'ERROR', 'info' => '参数错误!'];
        }
        $pay = &load_wechat('Pay');

        $prepay_id = $pay->getPrepayId(null, '扫码测试', $outer_no, $price * 100, url('index/pay/notify', null, null, true), 'NATIVE');
        if ($prepay_id === false) {
            return ['code' => 'ERROR', 'info' => '创建预支付码失败，' . $pay->errMsg];
        }
        return ['code' => 'SUCCESS', 'info' => '创建预支付码成功！', 'data' => $prepay_id];
    }
}
